package com.strongbj.iot.devices.dam.request.handle.dam;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.alibaba.fastjson.JSONObject;
import com.strongbj.core.message.IMessageHandle;
import com.strongbj.core.util.ByteUtil;
import com.strongbj.iot.devices.dam.common.AbstractTaskDelayedRunnable;
import com.strongbj.iot.devices.dam.common.DAMManager;
import com.strongbj.iot.devices.dam.common.ITaskManager;
import com.strongbj.iot.devices.dam.common.NetMapping;
import com.strongbj.iot.devices.dam.message.DAMMessageFactory;
import com.strongbj.iot.devices.dam.message.MQMessageOfDAM;
import com.strongbj.iot.devices.dam.request.entity.DeviceCodeEntity;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;

public class SetDeviceCodeHandle implements IMessageHandle<MQMessageOfDAM, Object> {
	private static Logger logger = LogManager.getLogger(SetDeviceCodeHandle.class.getName());
	private static final String ACTION_CODE = "setDeviceCode"; // 事件处理编码

	private final DAMMessageFactory damMessageFactory = new DAMMessageFactory(); // DAM消息工厂

	@Override
	public boolean isHandle(MQMessageOfDAM t) {
		if (t.getActioncode().equals(ACTION_CODE)) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 将设置网络参数的信息发送到硬件
	 */
	@Override
	public Object handle(ChannelHandlerContext ctx, MQMessageOfDAM t) {
		final DeviceCodeEntity dc = ((JSONObject) t.getAwsPostdata()).toJavaObject(DeviceCodeEntity.class);
		Channel channel = NetMapping.getInstance().getChannel(dc.getRackConverCode());
		ITaskManager taskManager = DAMManager.getTaskManager(dc.getRackConverCode());
		taskManager.addSendTask(new AbstractTaskDelayedRunnable() {
			@Override
			protected void taskRun() {
				sendDatasToDAM(channel,t,dc);
			}
			
		});
		return null;
	}
	
	private void sendDatasToDAM(Channel channel,MQMessageOfDAM t,DeviceCodeEntity dc) {
		if (channel != null && channel.isActive()) {
			final byte[] datas = DeviceCodeEntity2Bytes(t.getTimestamp(), dc); // 将网络参数对象转为byte数组，用于发送到dam硬件
			ByteBuf bs = Unpooled.copiedBuffer(datas);
			ChannelFuture cf = channel.writeAndFlush(bs);
			// TODO 添加监听,查看发送情况DEBUG
			cf.addListener(new ChannelFutureListener() {

				@Override
				public void operationComplete(ChannelFuture future) throws Exception {
					if (future.isSuccess()) {
						logger.info("WEB下发设置设备编号命令成功 编号:{} 下发命令={}  ", dc.getRackConverCode(),
								ByteUtil.byteArrToHexString(datas, true));
					} else {
						logger.error("WEB下发设置设备编号命令失败 编号:{} 下发命令={}  ", dc.getRackConverCode(),
								ByteUtil.byteArrToHexString(datas, true));
					}
				}
			});
		} else {
			logger.error("{} 主机没有找到指定channel", dc.getRackConverCode());
		}
	}

	/**
	 * 网络参数对象转byte数组
	 * 
	 * @param np
	 * @return
	 */
	private byte[] DeviceCodeEntity2Bytes(long time, DeviceCodeEntity dc) {
		// 创建
		byte[] codeDatas = new byte[3];
		// 3byte设备编号
		ByteUtil.hexStringToBytes(dc.getNewDeviceCode(), codeDatas, 0);

		// 创建DAM命令
		byte[] datas = damMessageFactory.createDAMMessage(ByteUtil.longToBytes(time), dc.getRackConverCode(), // 设备编号
				(byte) 0, // 设备类型，默认填0
				(byte) 0, // 版本号，默认填0
				(byte) 0x18, // 设置设备编号命令
				codeDatas // 设置设备编号
		); // 通过dam消息工厂获取指令
		return datas;
	}
}